package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.CommodityProducer;
import cn.hist.hfp.service.CommodityProducerService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.CommodityProducerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/producer")
public class CommodityProducerController {

    private final
    CommodityProducerService commodityProducerService;

    private final
    Authentication authentication;

    @Autowired
    public CommodityProducerController(CommodityProducerService commodityProducerService, Authentication authentication) {
        this.commodityProducerService = commodityProducerService;
        this.authentication = authentication;
    }

    @PostMapping
    public ResponseEntity<CommodityProducerVO> create(@RequestBody CommodityProducer commodityProducer, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        MyResponse<CommodityProducerVO> myResponse = new MyResponse<>();
        return myResponse.response(201, authentication.refreshToken(token), commodityProducerService.create(commodityProducer));
    }

    @GetMapping("/{id}")
    public CommodityProducerVO findOne(@PathVariable int id) {
        return commodityProducerService.findOneVO(id);
    }

    @GetMapping
    public List<CommodityProducerVO> findAll() {
        return commodityProducerService.findAll();
    }

    @PutMapping
    public ResponseEntity<CommodityProducerVO> update(@RequestBody CommodityProducer commodityProducer, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        MyResponse<CommodityProducerVO> myResponse = new MyResponse<>();
        return myResponse.response(200, authentication.refreshToken(token), commodityProducerService.update(commodityProducer));
    }

    @DeleteMapping
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), commodityProducerService.delete(id));
    }
}
